package com.lidong.framework.mybatis.util;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import com.lidong.framework.mybatis.annotion.factory.AnnotationConditionFactory;
import com.lidong.framework.mybatis.query.condition.Condition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ConditionUtil {
    private final static Logger LOGGER = LoggerFactory.getLogger(ConditionUtil.class);

	public static List<Condition> getConditions(Object target) {
		if (target == null) {
			return null;
		}
		List<Condition> ret = new ArrayList<Condition>();
		String methodName = null;
		try {
			Method[] methods = target.getClass().getMethods();
			for (Method method : methods) {
				methodName = method.getName();
				Annotation[] annotations = method.getAnnotations();
				if ((methodName.startsWith("get")) && (AnnotationConditionFactory.couldBuild(annotations))) {
					Object value = method.invoke(target, new Object[0]);
					for (Annotation annotation : annotations) {
						Condition condition = AnnotationConditionFactory.buildCondition(annotation, value);
						if (condition != null)
							ret.add(condition);
					}
				}
			}
			
			Field[] fields = target.getClass().getDeclaredFields();
			for (Field field : fields) {
			    field.setAccessible(true);
			    Annotation[] annotations = field.getAnnotations();
			    if (AnnotationConditionFactory.couldBuild(annotations)) {
			        Object value = field.get(target);
			        for (Annotation annotation : annotations) {
                        Condition condition = AnnotationConditionFactory.buildCondition(annotation, value);
                        if (condition != null)
                            ret.add(condition);
                    }
			    }
            }
		} catch (Exception e) {
		    LOGGER.error(methodName, e);
		}
		return ret;
	}
}
